package com.hwtx.form.domain.meta;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hwtx.form.persistence.entity.ApiDef;
import com.hwtx.form.persistence.mapper.ApiMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.hwtx.form.domain.FormConstants.API_PREFIX_URL;

@Component
@Slf4j
public class ApiMeta {

    private final Cache<String, ApiDef> cache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.DAYS).build();
    @Resource
    FunPermCache funPermCache;
    @Resource
    private ApiMapper apiMapper;

    public boolean isApi(String url) {
        return cache.getIfPresent(url) != null;
    }

    public boolean isAdminAuthApi(String url) {
        ApiDef apiDef = cache.getIfPresent(url);
        if (apiDef == null) {
            return false;
        }
        return apiDef.getAdminAuth() == 1;

    }

    @PostConstruct
    public void init() {
        apiMapper.selectList(new LambdaQueryWrapper<>()).forEach(apiDef -> {
            String url = API_PREFIX_URL + apiDef.getCode() + "/" + apiDef.getRetType().getValue();
            if (apiDef.getAdminAuth() == 0) {
                funPermCache.putNoAuth(url);
            }
            cache.put(url, apiDef);
        });
    }
}
